package com.qianfeng.lingshijia;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import fragment.BaseFragment;

/**
 * Created by Mr.xingkong on 2016/1/10.
 */
public class BaseActivity extends FragmentActivity {

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private Fragment showFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager = getSupportFragmentManager();
    }

    @Override
    public void startActivity(Intent intent) {
        startActivity(intent, R.anim.activity_in, R.anim.activity_out);
    }

    /**
     * activity切换动画效果
     *
     * @param intent
     * @param inAnim
     * @param outAnim
     */
    public void startActivity(Intent intent, int inAnim, int outAnim) {
        super.startActivity(intent);
        overridePendingTransition(inAnim, outAnim);
    }

    /**
     * Fragment管理方法
     *
     * @param resId
     * @param tClass
     * @param <T>
     */
    public <T extends BaseFragment> void fragmentManager(int resId, Class<T> tClass) {
        fragmentTransaction = fragmentManager.beginTransaction();
        Fragment mFragment = fragmentManager.findFragmentByTag(tClass.getName());

        if (showFragment != null) {
            //当前显示的fragment隐藏
            fragmentTransaction.hide(showFragment);
        }
        if (mFragment != null) {
            fragmentTransaction.show(mFragment);
            showFragment = mFragment;
        } else {
            //mFragment为空，表示该fragment在fm中还未被加入
            try {
                Fragment fragment = tClass.newInstance();
                fragmentTransaction.add(resId, fragment, tClass.getName());
                showFragment = fragment;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        fragmentTransaction.commit();
    }
}
